﻿using ElasticAgTest.Common;
using ElasticAgTest.Common.Extensions;
using ElasticAgTest.Extensions;
using ElasticAgTest.Models;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Events;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ElasticAgTest.ViewModels
{
    public class MainWindowViewModel : BindableBase, IConfigureService
    {
        #region 变量
        private readonly IRegionManager regionManager;
        private readonly IEventAggregator aggregator;
        private readonly IDialogHostService _dialogHostService;
        Param param;
        #endregion
        #region 属性
        private ObservableCollection<MenuBar> menuBars;
        public ObservableCollection<MenuBar> MenuBars
        {
            get { return menuBars; }
            set { SetProperty(ref menuBars, value); }
        }
        private string loginStr;
        public string LoginStr
        {
            get { return loginStr; }
            set { SetProperty(ref loginStr, value); }
        }
        private string userName = "";
        public string UserName
        {
            get { return userName; }
            set { SetProperty(ref userName, value); }
        }
        private bool isLogin = false;
        public bool IsLogin
        {
            get { return isLogin; }
            set { SetProperty(ref isLogin, value); }
        }
        #endregion
        #region 方法绑定
        private DelegateCommand<MenuBar> navigateCommand;
        public DelegateCommand<MenuBar> NavigateCommand =>
            navigateCommand ?? (navigateCommand = new DelegateCommand<MenuBar>(ExecuteNavigateCommand));
        private DelegateCommand appLoadedEventCommand;
        public DelegateCommand AppLoadedEventCommand =>
            appLoadedEventCommand ?? (appLoadedEventCommand = new DelegateCommand(ExecuteAppLoadedEventCommand));
        private DelegateCommand appClosedEventCommand;
        public DelegateCommand AppClosedEventCommand =>
            appClosedEventCommand ?? (appClosedEventCommand = new DelegateCommand(ExecuteAppClosedEventCommand));
        private DelegateCommand loginCommand;
        public DelegateCommand LoginCommand =>
            loginCommand ?? (loginCommand = new DelegateCommand(ExecuteLoginCommand));
        private DelegateCommand screenShootCommand;
        public DelegateCommand ScreenShootCommand =>
            screenShootCommand ?? (screenShootCommand = new DelegateCommand(ExecuteScreenShootCommand));

        void ExecuteScreenShootCommand()
        {
            aggregator.SendMessage("ScreenShoot", "App");
        }
        async void ExecuteLoginCommand()
        {
            if (LoginStr == "登录")
            {
                var dialogResult = await _dialogHostService.Password("登录");
                if (dialogResult.Result == Prism.Services.Dialogs.ButtonResult.OK)
                {
                    string password = dialogResult.Parameters.GetValue<string>("Password");
                    if (password == GetPassWord())
                    {
                        IsLogin = true;
                        UserName = "JS Leader";
                        aggregator.SendMessage("Login", "App");
                        LoginStr = "登出";
                        aggregator.SendMessage("登录成功!");
                    }
                }
            }
            else
            {
                IsLogin = false;
                UserName = "";
                aggregator.SendMessage("Logout", "App");
                LoginStr = "登录";
                aggregator.SendMessage("登出");
            }
        }
        void ExecuteAppClosedEventCommand()
        {
            aggregator.SendMessage("AppClosed", "App");
        }
        async void ExecuteAppLoadedEventCommand()
        {
            var r1 = await Task.Run(() => { return PLCModbus.Instance.Connect(); });
            if (!r1)
            {
                MessageBox.Show("PLC连接失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            var r2 = MCUSerial.Instance.Open(param.MCU_COM);
            if (!r2)
            {
                MessageBox.Show("MCU连接失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            aggregator.SendMessage("AppLoaded", "App");
        }
        void ExecuteNavigateCommand(MenuBar obj)
        {
            if (obj == null || string.IsNullOrWhiteSpace(obj.NameSpace))
                return;
            //regionManager.Regions[PrismManager.MainViewRegionName].RequestNavigate(obj.NameSpace);
            aggregator.SendMessage(obj.NameSpace, "Menu");
        }
        #endregion
        #region 构造函数
        public MainWindowViewModel(IContainerProvider containerProvider,IRegionManager regionManager, IDialogHostService dialogHostService)
        {
            _dialogHostService = dialogHostService;
            aggregator = containerProvider.Resolve<IEventAggregator>();
            MenuBars = new ObservableCollection<MenuBar>();
            this.regionManager = regionManager;
            LoginStr = "登录";
            LoadParam();
        }
        #endregion
        #region 界面
        void CreateMenuBar()
        {
            //MenuBars.Add(new MenuBar() { Icon = "Home", Title = "测试模式", NameSpace = "IndexView" });
            //MenuBars.Add(new MenuBar() { Icon = "Cog", Title = "设置", NameSpace = "SettingsView" });
            MenuBars.Add(new MenuBar() { Icon = "ChartLine", Title = "弹力曲线", NameSpace = "Home" });
            MenuBars.Add(new MenuBar() { Icon = "ChartSankey", Title = "寿命曲线", NameSpace = "Lifetime" });
            MenuBars.Add(new MenuBar() { Icon = "ChartAreasplineVariant", Title = "历史曲线", NameSpace = "History" });
            MenuBars.Add(new MenuBar() { Icon = "Cog", Title = "设置", NameSpace = "Settings" });
        }
        public void Configure()
        {
            CreateMenuBar();
            regionManager.Regions[PrismManager.MainViewRegionName].RequestNavigate("IndexView");
        }
        #endregion
        #region 功能函数
        void LoadParam()
        {
            try
            {
                //Json序列化，从文件读取
                string jsonString = File.ReadAllText(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Param.json"));
                param = JsonConvert.DeserializeObject<Param>(jsonString);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
        private string GetPassWord()
        {
            int day = System.DateTime.Now.Day;
            int month = System.DateTime.Now.Month;
            string ss = (day + month).ToString();
            string passwordstr = "";
            for (int i = 0; i < 4 - ss.Length; i++)
            {
                passwordstr += "0";
            }
            passwordstr += ss;
            return passwordstr;
        }
        #endregion
    }
}
